<?php
/**
 * Created by PhpStorm.
 * User: George
 * Date: 2017/9/25
 * Time: 11:06
 */

namespace AdminBundle\Task;

use AdminBundle\Entity\LogRoomJoined;
use AdminBundle\Entity\LogRoomUser;

/**
 * 大群,大于100人的群
 * 响应包体格式
 * 说明: 返回微信群对应的二维码(图片[jpg,png,gif]),如微信号在服务端被禁用则不返回对应数据.
 * name: 群名字
 * qrcode: 二维码下载地址
 * id:群唯一ID
 * count: 当前群内成员数量
 * status: 1表示位40人以下群，2表示40-100人群，3表示100-500人群，0表示暴力拉取的群。当前默认值为0
 * {"code":0,"msg":"ok","time":1482653499,"data":{"name":"群名字1","qrcode":"二维码下载地址http:\/\/admin.bjtwtx.com\/upload\\2016\\12\\19\\5788f7e6c468ec5cf0731ec4098f14bb.jpeg","id":"群ID","count":0,"status":0}}
 * 马甲号入群的二维码
 * 获取马甲号入群的二维码
 * Class QrcodeJoinRoomTask
 * @package AdminBundle\Task
 */
class QrcodeJoinRoomTask extends Task
{
    const SOURCE_TYPE_LABOUR = 2; //营销好友
    const ROOM_GT_100 = 3;        // 3表示100-500人群

    private $contacts = [];
    private $room = [];

    /**
     * 返回
     * @return null
     */
    public function jsonTask()
    {
        $data = [
            'app' => 'api', 'os' => 'ios', 'deviceid' => $this->task->getDeviceName(),
            'data' =>
                [
                    'token' => $this->task->getAction(),
                    'webchat' => [$this->task->getWebchatUsername(), $this->task->getNote()]
                ]
        ];

        $url = 'http://admin.bjtwtx.com/api/partner/group/qr/auth';

        $json = $this->httpJson($url, $data);
        if ($json == null || $json['code'] != 0) {
            return null;
        }

        $user_id = $this->task->getMethod();

        $room = $json['data'];
        $this->room = $room;
        $this->roomUser($room, $user_id);

        $friends = [];
        if ($room['status'] < self::ROOM_GT_100) {
            // 获取联系人
            // todo: 根据营销好友的身份标签邀请入群
            $contacts = $this->getContacts($user_id, self::SOURCE_TYPE_LABOUR, '');
            foreach ($contacts as $contact) {
                $friends[] = [
                    'nickname' => $contact['nickname'],
                    'username' => $contact['userName'],
                    'mobile' => $contact['mobile']
                ];
            }

            $this->logRoomJoined($this->em, $contacts);
        }

        return json_encode([
            'name' => $room['name'],
            'qrcode' => $room['qrcode'],
            'friends' => $friends // array_column($this->contacts, 'userName')
        ]);
    }

    /**
     * 马甲入群记录
     * @param $room
     * @param $userId
     * @return LogRoomUser
     */
    private function roomUser($room, $userId)
    {
        // todo: 根据营销好友的身份标签邀请入群
        $em = $this->em;

        $logRoomUser = $em->getRepository('AdminBundle:LogRoomUser')->findOneBy([
            'webchatId' => $userId,
            'roomId' => $room['id']
        ]);
        if ($logRoomUser != null) {
            return $logRoomUser;
        }
        $logRoomUser = new LogRoomUser();
        $logRoomUser->setCtime(new \DateTime())
            ->setWebchatId($this->task->getMethod())
            ->setWebchatUsername($this->task->getWebchatUsername())
            ->setRoomId($room['id'])
            ->setRoomName($room['name'])
            ->setRoomTags('')
            ->setRoomType($room['status'])
            ->setRoomQrcode($room['qrcode'])
            ->setStatus(1);
        $em->persist($logRoomUser);
        $em->flush();
    }

    /**
     * 根据微信号选择营销好友加入群
     * 规则：随机
     * @return array
     */
    private function getContacts($user_id, $source_type, $tags, $count = 50)
    {
        $friends = $this->em->getRepository('AdminBundle:BaseWebchatMember')->labourJoinRoom($user_id, $source_type, $tags, $count);
        if ($friends == null)
            return [];
        return $friends;
    }

    /**
     * 执行数据库操作
     * @param $em
     */
    public function logRoomJoined($em, $contacts)
    {
        if (empty($contacts))
            return;
        $room = $this->room;
        foreach ($contacts as $contact) {
            $logRoomJoined = new LogRoomJoined();

            $logRoomJoined->setCtime(new \DateTime())
                ->setWebchatId($this->task->getMethod())
                ->setWebchatUsername($this->task->getWebchatUsername())
                ->setMemberUserId($contact['mobile'])
                ->setRoomId($room['id'])
                ->setRoomName($room['name'])
                ->setRoomTags('')
                ->setRoomType($room['status'])
                ->setStatus(1);

            $em->persist($logRoomJoined);
        }
        $em->flush();
    }
}